package com.yzh.openai.infrastructure.repository;

import com.yzh.openai.domain.weixin.model.valobj.UserAccountConfigVO;
import com.yzh.openai.domain.weixin.repository.IWeiXinRepository;
import com.yzh.openai.infrastructure.dao.UserAccountMapper;
import com.yzh.openai.infrastructure.po.UserAccountPO;
import com.yzh.openai.infrastructure.redis.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 微信仓储服务
 */
@Slf4j
@Repository
public class WeiXinRepository implements IWeiXinRepository {
    private static final String Key = "wx_code";
    @Resource
    private UserAccountMapper userAccountMapper;
    @Resource
    private IRedisService redisService;

    @Override
    public int insertUserAccount(String openid) {
        UserAccountPO userAccount = new UserAccountPO().builder()
                .openid(openid)
                .totalQuota(UserAccountConfigVO.totalQuota)
                .surplusQuota(UserAccountConfigVO.surplusQuota)
                .modelTypes(UserAccountConfigVO.modelTypes)
                .status(UserAccountConfigVO.status)
                .build();

        return userAccountMapper.insertUserAccount(userAccount);
    }

    @Override
    public String genCode(String openid) {
        String code = redisService.getValue(Key + "_" + openid);
        if (StringUtils.isNotBlank(code)) return code;
        //生成code
        RLock rLock = redisService.getLock(Key);
        try {
            rLock.lock(15, TimeUnit.SECONDS);

            String genCode = RandomStringUtils.randomNumeric(4);
            //防重，重新生成
            for (int i = 0; i < 10 && StringUtils.isNotBlank(redisService.getValue(Key + "_" + genCode)); i++) {
                if (i < 3) {
                    genCode = RandomStringUtils.randomNumeric(4);
                } else if (i < 6) {
                    genCode = RandomStringUtils.randomNumeric(5);
                }else if (i < 9) {
                    genCode = RandomStringUtils.randomNumeric(6);
                    log.warn("注意！已生成6位访问码，重复概率过高。");
                }else {
                    return "您的验证码获取失败，请重新回复666获取";
                }
            }

            //存值(3min 有效)
            redisService.setValue(Key + "_" + genCode, openid, 1000 * 60 * 3);
            redisService.setValue(Key + "_" + openid, genCode, 1000 * 60 * 3);

            return genCode;
        } finally {
            rLock.unlock();
        }
    }
}
